package com.chen.seckill.service.impl;

import com.chen.seckill.dao.PromoMapper;
import com.chen.seckill.pojo.Promo;
import com.chen.seckill.service.PromoService;
import com.chen.seckill.service.bo.PromoBO;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

@Service
public class PromoServiceImpl implements PromoService {

    @Autowired
    private PromoMapper promoMapper;

    @Override
    public PromoBO getPromoByItemId(Integer itemId) {
        // 获取对应商品的秒杀活动信息
        Promo promo = promoMapper.selectByItemId(itemId);

        // DO转化为BO
        PromoBO promoBO = convertFromPromo(promo);

        if (promoBO == null) {
            return null;
        }

        // 判断当前时间是否有秒杀活动正在进行，或即将开始
        // 如果活动开始时间晚于当前时间，则设置状态为1还未开始
        if (promoBO.getStartDate().isAfterNow()) {
            promoBO.setStatus(1);
            // 如果活动结束时间早于当前时间，则设置状态为3已结束
        } else if (promoBO.getEndDate().isBeforeNow()) {
            promoBO.setStatus(3);
        } else {// 其余时间都是正在进行
            promoBO.setStatus(2);
        }
        return promoBO;
    }

    private PromoBO convertFromPromo(Promo promo) {
        if (promo == null) {
            return null;
        }
        PromoBO promoBO = new PromoBO();
        BeanUtils.copyProperties(promo, promoBO);
        // 数据类型不一致的数据，手动赋值
        promoBO.setPromoItemPrice(BigDecimal.valueOf(promo.getPromoItemPrice()));
        promoBO.setStartDate(new DateTime(promo.getStartDate()));
        promoBO.setEndDate(new DateTime(promo.getEndDate()));

        return promoBO;
    }
}
